package com.captjack.thrift;

import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;

/**
 * @author admin
 */
public class Server {

    public static void main(String[] args) {
        try {
            TServer server = genNioServer();
            // 启动 Server
            server.serve();
            System.out.println("start success!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return server
     * @throws Exception 异常
     */
    private static TServer genNioServer() throws Exception {
        // 创建 TProcessor
        TProcessor tprocessor = new ThriftHelloService.Processor<ThriftHelloService.Iface>(new ThriftHelloServiceImpl());
        // 创建 TServerTransport, TServerSocket 继承于 TServerTransport
        TNonblockingServerSocket nonblockingServerSocket = new TNonblockingServerSocket(7003);
        //
        TNonblockingServer.Args tArgs = new TNonblockingServer.Args(nonblockingServerSocket);
        tArgs.processor(tprocessor);
        // 使用二进制协议
        tArgs.protocolFactory(new TBinaryProtocol.Factory());
        // 创建 TServer
        return new TNonblockingServer(tArgs);
    }

    /**
     * @return server
     * @throws Exception 异常
     */
    private static TServer genSimpleServer() throws Exception {
        // 创建 TProcessor
        TProcessor tprocessor = new ThriftHelloService.Processor<ThriftHelloService.Iface>(new ThriftHelloServiceImpl());
        // 创建 TServerTransport, TServerSocket 继承于 TServerTransport
        TServerTransport serverTransport = new TServerSocket(7003);
        //
        TServer.Args tArgs = new TServer.Args(serverTransport);
        tArgs.processor(tprocessor);
        // 使用二进制协议
        tArgs.protocolFactory(new TBinaryProtocol.Factory());
        // 创建 TServer
        return new TSimpleServer(tArgs);
    }

}
